package com.hexb.core.web;

import com.hexb.core.model.ValueEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * @Package : com.feitian.airlines.config
 * @Author : hexb
 * @Date : 2018-08-29 13:37
 */
public class IntToValueEnumConverterFactory implements ConverterFactory<Integer, ValueEnum> {

    @Override
    public <T extends ValueEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
        if (!targetType.isEnum()) {
            throw new UnsupportedOperationException("只支持转换到枚举类型");
        }
        return new IntToValueEnumConverter(targetType);
    }

    private static class IntToValueEnumConverter<T extends ValueEnum> implements Converter<Integer, T> {

        private final Class<T> enumType;

        public IntToValueEnumConverter(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(Integer source) {
            for (T t : enumType.getEnumConstants()) {
                if (t.getValue() == source) {
                    return t;
                }
            }
            return null;
        }
    }
}
